import {appConfig} from './config'
import {token} from './token'

const send = (url, data = {}, method = 'POST', showLoading = true, base_url = '') => {
    uni.showLoading({
        title: '加载中'
    })
    return new Promise((resolve) => {
        uni.request({
            method: method,
            url: (base_url ? base_url : appConfig.apiUrl) + url,
            data: data,
            header: (() => {
                const tokeValue = token.get()
                let config = {}
                if (tokeValue) {
                    config[appConfig.sendTokenKey] = tokeValue
                }
                config['content-type']='application/json'
                return config
            })(),
            success: (res) => {
				uni.hideLoading()
				if(res.data.status==500&&res.data.message.equals('Token失效，请重新登录')){
					uni.navigateTo({
						url:'/pages/public/login'
					})
				}else{
					resolve(res.data)
				}
                
                
            },
			fail: (res) => {
				uni.hideLoading()
				resolve(res.data)
			}
        })
    })
}

const login = (url, data = {}, method = 'POST', showLoading = true, base_url = '') => {
    uni.showLoading({
        title: '加载中'
    })
    return new Promise((resolve) => {
        uni.request({
            method: method,
            url: (base_url ? base_url : appConfig.apiUrl) + url,
            data: data,
            header: (() => {
                let config = {}
                config['content-type']='application/json'
                return config
            })(),
            success: (res) => {
                uni.hideLoading()
                resolve(res.data)
            }
        })
    })
}

export const request = {
    get: (url, data) => {
        return send(url, data, 'GET')
    },
    post: (url, data) => {
        return send(url, data, 'POST')
    },
	login: (data) => {
		return login('/sys/mLogin',data)
	}
}
